package ar.edu.itba.it.cg.grupo01.impl;

import java.util.Iterator;
import java.util.List;

import javax.vecmath.Vector2f;

import ar.edu.itba.it.cg.grupo01.api.CameraInterface;
import ar.edu.itba.it.cg.grupo01.api.Ray;

public class MultipleRays implements Iterator<CameraRay> {
	
	private final CameraInterface camera;
	private final int width;
	private final int height;
	private float x;			// ray x coordinate
	private float y;			// ray y coordinate
	private int i;
	private int j;
	private List<Vector2f> move;
	
	private int currentray;
	private float quantum;
	private int n;
	
	public MultipleRays(final CameraInterface camera, int n) {
		
		this.camera = camera;
		this.width = camera.getxResolution();
		this.height = camera.getyResolution();
		this.move = Utilities.subdividePixel(1, n);
		initialize();
	}
	
	private void initialize() {
		
		this.i = 0;
		this.j = 0;
		this.x = 0.0f;
		this.y = 0.0f;
		this.currentray = 0;		
	}
	
	private void reset() {
		
		currentray = 0;
		this.j = (j + 1) % width;
		this.i = (j == 0) ? i + 1 : i;
//		this.x = this.j;
//		this.y = this.j;
//		
	}
	
	@Override
	public boolean hasNext() {
		return (i < height) && (j < width);
	}

	@Override
	public CameraRay next() {
		
		Vector2f delta = move.get(currentray);
		y = j + delta.y;
		x = i + delta.x;
		currentray = currentray + 1;
		
		if(x >= (camera.getyResolution() -1))
			x = (camera.getyResolution() -1);
		
		if(y >= (camera.getxResolution() -1))
			y = (camera.getxResolution() -1);
		
		Ray ray = camera.getRay(x,y);
		CameraRay cameraRay = new CameraRay(ray,i,j);
		
		if (!needsMoreRaysForPixel())
			reset();
		
		return cameraRay;
	}

	@Override
	public void remove() {
		
		throw new UnsupportedOperationException();
	}
	
	public boolean needsMoreRaysForPixel() {
		return currentray < move.size();
	}
}
